import {
  DeleteOutlined,
} from '@ant-design/icons';
import { Button, message, Popconfirm } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { queryFile, deleteFile } from './service';
import type { FileItem, TableListPagination } from './data';

/**
 * 批量删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: FileItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    const res = await deleteFile({
      key: selectedRows.map((row) => row.id),
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        message.success(res.message);
        return true;
      } else {
        message.error(res.message);
        return false;
      }
    } else {
      message.error('请求超时，请稍后重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 删除节点
 *
 * @param record
 */
const handleSingleRemove = async (record: FileItem) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deleteFile({
      key: [record.id],
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        message.success(res.message);
        return true;
      } else {
        message.error(res.message);
        return false;
      }
    } else {
      message.error('请求超时，请稍后重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<FileItem[]>([]);

  // 表头，列表渲染设置
  // @ts-ignore
  const columns: ProColumns<FileItem>[] = [
    // 关键字搜索
    {
      title: 'keyword',
      hideInTable: true,
      hideInForm: false,
      dataIndex: 'keyword',
      formItemProps: { label: '关键字' },
    },
    // 列表字段
    {
      title: 'ID',
      // copyable: true,  // 展示复制按钮
      dataIndex: 'id', // 数据索引
      width: 60,
      // ellipsis: true,  // 超长度自动收缩
      // tip: 'ID',    // 提示文字tip
      sorter: (a, b) => a.id - b.id, // 开启排序
      search: false, // 是否在header展示此搜索框
      hideInTable: false, // 不在表格中展示
      hideInSearch: true, // 不在搜索框中展示
      editable: false,
    },
    {
      title: '文件名',
      dataIndex: 'name',
      valueType: 'text',
      hideInSearch: true,
      render: (_, { name, path }) => {
        return (
          <a download={true} href={path} target={'_blank'} rel="noopener noreferrer">
            {name}
          </a>
        );
      },
    },
    {
      title: '文件大小',
      dataIndex: 'size',
      valueType: 'text',
      hideInSearch: true,
      align: 'right',
    },
    {
      title: '上传人',
      dataIndex: 'uploadBy',
      valueType: 'text',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '上传时间',
      width: 150,
      dataIndex: 'createdTime',
      valueType: 'dateTime',
      align: 'center',
      search: false,
      sorter: (a, b) => {
        // 开启排序
        // 时间的排序，需要先转存时间戳
        const aTime = new Date(a.createdTime).getTime();
        const bTime = new Date(b.createdTime).getTime();
        return aTime - bTime;
      },
    },
    {
      title: 'MD5',
      dataIndex: 'md5',
      valueType: 'text',
      hideInSearch: true,
      copyable: true,
    },
    {
      title: '操作',
      key: 'option',
      align: 'right',
      valueType: 'option',
      render: (text, record) => {
        if (record.tempTag) {
          return (
            <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={async () => {
              const success = await handleSingleRemove(record);
              if (success) {
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}>
              <a style={{color: "red"}} ><DeleteOutlined /> 删除</a>
            </Popconfirm>
          );
        } else {
          return (
            <Button size={'small'} title={'非临时文件，不可删除'} disabled={true}>
              <DeleteOutlined /> 删除
            </Button>
          );
        }
      },
    },
  ];

  // @ts-ignore
  return (
    <PageContainer pageHeaderRender={false}>
      <ProTable<FileItem, TableListPagination>
        headerTitle="附件列表"
        actionRef={actionRef}
        rowKey="id"

        // 设置分页参数
        pagination={{ defaultPageSize: 10, showSizeChanger: true }}

        // 表格数据源
        request={queryFile}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              行 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
